import { Injectable } from '@nestjs/common';
import { PermissionEntity } from './permission.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(PermissionEntity)
    private usersRepository: Repository<PermissionEntity>,
  ) {}
  // 增加
  async create(createRoleDto: any): Promise<any> {
    const { name, password } = createRoleDto;
    delete createRoleDto.id;
    const isExist = await this.usersRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 0) {
      return {
        statusCode: 202,
        message: '已存在',
      };
    }

    return await this.usersRepository.save(createRoleDto);
  }

  // 软删除
  async delete(removeUserDto: any): Promise<any> {
    const { ids } = removeUserDto;
    return this.usersRepository.softDelete(ids);
  }
  //   查详情
  async findOne(id: string): Promise<any> {
    let res = await this.usersRepository
      .createQueryBuilder()
      .where([{ id: id }])
      .getOne();
    console.log(res);
    return res;
  }

  // 更新
  async update(updateUserData): Promise<any> {
    const { id, updateUserDto } = updateUserData;
    // updateUserDto.updatedAt = new Date();
    const { name } = updateUserDto;

    const isExist = await this.usersRepository.count({
      where: {
        name,
      },
    });
    if (isExist > 1) {
      return {
        statusCode: 201,
        message: '已存在',
      };
    }
    return await this.usersRepository.update(id, updateUserDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, page = 1, limit = 10 } = query;
    const skip = (page - 1) * limit;

    let params = {
      skip,
      take: limit,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = Object.assign(whereParams, {
        name: Like(`%${keyword}%`),
      });
    }

    params = Object.assign(
      //   {
      //     select: ['id', 'name', 'updatedAt', 'status'],
      //   },
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updated_at: 'DESC',
        },
      },
    );

    const [data, total] = await this.usersRepository.findAndCount(params);

    return {
      total,
      data,
    };
  }
}
